package com.micangcaihang.micang.mvp.task.ui;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocationClient;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.luck.picture.lib.permissions.Permission;
import com.luck.picture.lib.permissions.RxPermissions;
import com.micangcaihang.common.base.activity.BaseActivity;
import com.micangcaihang.common.base.fragment.BaseDataBingFragment;
import com.micangcaihang.common.base.popup.BasePopupWindow;
import com.micangcaihang.common.utils.ALog;
import com.micangcaihang.common.utils.KeyboardUtils;
import com.micangcaihang.common.utils.TimeUtils;
import com.micangcaihang.common.utils.ToastUtils;
import com.micangcaihang.common.widget.titlebar.TitleBar;
import com.micangcaihang.micang.R;
import com.micangcaihang.micang.adapter.TaskTabAdapter;
import com.micangcaihang.micang.databinding.ActivityTaskDetailFBinding;
import com.micangcaihang.micang.entity.ReBackEntity;
import com.micangcaihang.micang.entity.TabTaskEntity;
import com.micangcaihang.micang.entity.UserInfoSp;
import com.micangcaihang.micang.mvp.task.contract.FTaskDetailContract;
import com.micangcaihang.micang.mvp.task.presenter.FTaskDetailPresenter;
import com.micangcaihang.micang.util.DialogHelper;
import com.micangcaihang.micang.util.LocationUtil;
import com.micangcaihang.micang.view.ReBackPopup;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * <pre>
 *     author : Fandy
 *     e-mail : fandayongfly@gmail.com
 *     time   : 2017/7/30
 *     update : 2017/7/30
 *     desc   : 调评任务详情首页
 *     version: 1.0
 * </pre>
 */

public class FTaskDetailActivity extends BaseActivity<FTaskDetailPresenter,
        ActivityTaskDetailFBinding> implements FTaskDetailContract.View {
    private static final int REBACK_TASK = 0x12;
    private static final int APPLY_STOP_TASK = 0x13;
    private String id;
    private String reback;
    /**
     * 1.新任务
     * 2.处理中
     * 3.资料有误
     * 4.资料不齐全
     */
    private int type;

    private BaseDataBingFragment[] mFragments = new BaseDataBingFragment[13];

    private TaskTabAdapter mTaskTabAdapter;

    private int currentTabPos;
    private StringBuilder title = new StringBuilder();
    private ReBackPopup mReBackPopup;
    private RxPermissions mRxPermissions;
    private int status;

    /**
     * 获取资源文件布局
     *
     * @return 资源布局文件layout
     */
    @Override
    protected int getLayoutId() {
        return R.layout.activity_task_detail_f;
    }

    @Override
    protected void beforeInitView(Bundle savedInstanceState) {
        super.beforeInitView(savedInstanceState);
        if (savedInstanceState == null) {
            mFragments[0] = FTaskLoansInfoFragment.newInstance(id);
            mFragments[1] = FTaskProductInfoFragment.newInstance(id);
            mFragments[2] = FTaskBorrowerInfoFragment.newInstance(id);
            mFragments[3] = FTaskCommonOwnerInfoFragment.newInstance(id);
            mFragments[4] = FTaskPracticalUserInfoFragment.newInstance(id);
            mFragments[5] = FTaskBondsmanInfoFragment.newInstance(id);
            mFragments[6] = FTaskCommonBorrowInfoFragment.newInstance(id);
            mFragments[7] = FTaskFaceOpinionLoanConditionFragment.newInstance(id);
            mFragments[8] = FTaskCostDetailFragment.newInstance(id);
            mFragments[9] = FTaskBorrowerAccessoryFragment.newInstance(id);
            mFragments[10] = FTaskHouseProveAccessoryFragment.newInstance(id);
            mFragments[11] = FTaskOtherPeopleAccessoryFragment.newInstance(id);
            mFragments[12] = FTaskOnePledgeLeaseAccessoryFragment.newInstance(id);
            loadMultipleRootFragment(R.id.main_root, 0, mFragments);
        } else {
            // 这里库已经做了Fragment恢复,所有不需要额外的处理了, 不会出现重叠问题
            for (int i = 0; i < mFragments.length; i++) {
                ALog.e(TAG, "initFragments" + i);
                mFragments[i] = findFragment(mFragments[i].getClass());
            }
        }
    }

    /**
     * 获取传递的bundle数据
     *
     * @param extras
     */
    @Override
    protected void getBundleExtras(Bundle extras) {
        type = extras.getInt("type");
        id = extras.getString("id");
        reback = extras.getString("reback", "0");
        status = extras.getInt("status");
    }

    @Override
    public void initView() {
        super.initView();
        if (status == 3 || status == 4) {
            mViewBinding.tvReback.setVisibility(View.GONE);
        } else {
            mViewBinding.tvReback.setVisibility(View.VISIBLE);
        }
        mReBackPopup = new ReBackPopup(this);
        switch (type) {
            case 1:
                mViewBinding.titleBar.setTitleText(mContext.getResources().getString(R.string.new_task));
                break;
            case 2:
                mViewBinding.titleBar.setTitleText(mContext.getResources().getString(R.string.to_be_treated));
                break;
            case 3:
                // 先清除掉默认的粗体，否则下面设置Typeface.NORMAL不会生效
                mViewBinding.titleBar.getTitleCtv().getPaint().setTypeface(Typeface.DEFAULT);
                // 取消默认的单行
                mViewBinding.titleBar.getTitleCtv().setSingleLine(false);
                // 设置行间距
                mViewBinding.titleBar.getTitleCtv().setLineSpacing(3, 1);
                String data_error = mContext.getResources().getString(R.string.data_error);
                SpannableString titleSs = new SpannableString(data_error + "\n" + "查看原因");
                titleSs.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.white_text)), 0, data_error.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                titleSs.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelOffset(R.dimen.font_18), false), 0, data_error.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                titleSs.setSpan(new StyleSpan(Typeface.NORMAL), 0, data_error.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                titleSs.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.common_title_color)), data_error.length(), titleSs.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                titleSs.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelOffset(R.dimen.font_13), false), data_error.length(), titleSs.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                titleSs.setSpan(new StyleSpan(Typeface.NORMAL), data_error.length(), titleSs.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                mViewBinding.titleBar.setTitleText(titleSs);
                mViewBinding.titleBar.setTitleDrawable(R.drawable.ic_triangle_black_top);
                break;
            case 4:
                // 先清除掉默认的粗体，否则下面设置Typeface.NORMAL不会生效
                mViewBinding.titleBar.getTitleCtv().getPaint().setTypeface(Typeface.DEFAULT);
                // 取消默认的单行
                mViewBinding.titleBar.getTitleCtv().setSingleLine(false);
                // 设置行间距
                mViewBinding.titleBar.getTitleCtv().setLineSpacing(3, 1);
                String data_incomplete = mContext.getResources().getString(R.string.data_incomplete);
                SpannableString titleSs1 = new SpannableString(data_incomplete + "\n" + "查看原因");
                titleSs1.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.white_text)), 0, data_incomplete.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                titleSs1.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelOffset(R.dimen.font_18), false), 0, data_incomplete.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                titleSs1.setSpan(new StyleSpan(Typeface.NORMAL), 0, data_incomplete.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                titleSs1.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.common_title_color)), data_incomplete.length(), titleSs1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                titleSs1.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelOffset(R.dimen.font_13), false), data_incomplete.length(), titleSs1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                titleSs1.setSpan(new StyleSpan(Typeface.NORMAL), data_incomplete.length(), titleSs1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                mViewBinding.titleBar.setTitleText(titleSs1);
                mViewBinding.titleBar.setTitleDrawable(R.drawable.ic_triangle_black_top);
                break;
            default:
                break;
        }
        mViewBinding.setClickHadnler(new ClickHandler());
    }

    public String getWatertitle() {
        return title.toString();
    }

    @Override
    protected void initData() {
        super.initData();
        mRxPermissions = new RxPermissions(this);
        title.append("考察员：" + UserInfoSp.getInstance().getUsername())
                .append("拍照时间：" + TimeUtils.getNowString() + "\n")
                .append("位置：未知\n")
                .append("经纬度：未知");
        ((SimpleItemAnimator) mViewBinding.tab.getItemAnimator()).setSupportsChangeAnimations(false);
        mViewBinding.tab.getItemAnimator().setChangeDuration(0);
        mViewBinding.tab.setAnimation(null);
        List<TabTaskEntity> list = new ArrayList<>();
        list.add(new TabTaskEntity(mContext.getResources().getString(R.string.task_loans_info), true));
        list.add(new TabTaskEntity(mContext.getResources().getString(R.string.task_product_info), false));
        list.add(new TabTaskEntity(mContext.getResources().getString(R.string.task_borrower_info), false));
        list.add(new TabTaskEntity(mContext.getResources().getString(R.string.task_common_owner_info), false));
        list.add(new TabTaskEntity(mContext.getResources().getString(R.string.task_practical_user_info), false));
        list.add(new TabTaskEntity(mContext.getResources().getString(R.string.task_bondsman_info), false));
        list.add(new TabTaskEntity(mContext.getResources().getString(R.string.task_common_borrow_info), false));
        list.add(new TabTaskEntity(mContext.getResources().getString(R.string.task_face_opinion_loan_condition), false));
        list.add(new TabTaskEntity(mContext.getResources().getString(R.string.task_cost_detail), false));
        list.add(new TabTaskEntity(mContext.getResources().getString(R.string.task_borrower_accessory), false));
        list.add(new TabTaskEntity(mContext.getResources().getString(R.string.task_house_prove_accessory), false));
        list.add(new TabTaskEntity(mContext.getResources().getString(R.string.task_other_people_accessory), false));
        list.add(new TabTaskEntity(mContext.getResources().getString(R.string.task_one_pledge_lease_accessory), false));
        mTaskTabAdapter = new TaskTabAdapter(R.layout.item_tab_task_f, list);
        mViewBinding.tab.setLayoutManager(new LinearLayoutManager(this));
        mViewBinding.tab.setAdapter(mTaskTabAdapter);
    }

    /**
     * 初始化按钮监听
     */
    @Override
    protected void initListener() {
        mRxPermissions.requestEach(
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS
        )
                .subscribe(new Observer<Permission>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull Permission permission) {
                        if (permission.granted) {
                            startLocation();
                        } else {
                            new MaterialDialog.Builder(FTaskDetailActivity.this)
                                    .content("你没有开启应用所需要的权限,您到设置页面开启")
                                    .positiveText("去设置")
                                    .negativeText("取消")
                                    .onPositive((dialog, which) -> {
                                        dialog.dismiss();
                                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                        intent.setData(Uri.parse("package:" + mContext.getPackageName()));
                                        mContext.startActivity(intent);
                                    })
                                    .show();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
        mViewBinding.tab.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                KeyboardUtils.hideSoftInput(FTaskDetailActivity.this);
                if (mTaskTabAdapter.getData().get(position).isSelect()) {
                    return;
                } else {
                    checkIsSaveData(position, adapter);
                }
            }
        });
        mViewBinding.titleBar.setDelegate(new TitleBar.Delegate() {
            @Override
            public void onClickLeftCtv() {
                new MaterialDialog.Builder(FTaskDetailActivity.this)
                        .content("退出之后无法继续编辑,请保存后再进行退出.")
                        .positiveText("确定")
                        .negativeText("取消")
                        .onPositive((dialog, which) -> finish())
                        .show();
            }

            @Override
            public void onClickTitleCtv() {
                if (status == 3) {
                    mPresenter.loadRebackData(id, "1");
                } else if (status == 4) {
                    mPresenter.loadRebackData(id, "2");
                }
            }

            @Override
            public void onClickRightCtv() {

            }

            @Override
            public void onClickRightSecondaryCtv() {//预览
                startActivity(DDeliveryActivity.class);
            }
        });
        mReBackPopup.setOnDismissListener(new BasePopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mViewBinding.titleBar.setTitleDrawable(R.drawable.ic_triangle_black_bottom);
            }
        });
    }

    /**
     * 检车是否已经点击当前fragment的保存,如果已经点击了保存则可以切换页面
     * 否则强制提示用户去保存信息
     *
     * @param tabNum
     * @param adapter
     */
    private void checkIsSaveData(int tabNum, BaseQuickAdapter adapter) {
        switch (currentTabPos) {
            case 0:
                FTaskLoansInfoFragment fTaskLoansInfoFragment = (FTaskLoansInfoFragment) getSupportFragmentManager().getFragments().get(currentTabPos);
                if (!fTaskLoansInfoFragment.isSaveData()) {
                    DialogHelper.showSaveDialog(this, () -> fTaskLoansInfoFragment.saveData(), () -> updateTab(tabNum, adapter));

                } else {
                    updateTab(tabNum, adapter);
                }
                break;
            case 1:
                FTaskProductInfoFragment fTaskProductInfoFragment = (FTaskProductInfoFragment) getSupportFragmentManager().getFragments().get(currentTabPos);
                if (!fTaskProductInfoFragment.isSaveData()) {
                    DialogHelper.showSaveDialog(this, () -> fTaskProductInfoFragment.saveData(), () -> updateTab(tabNum, adapter));

                } else {
                    updateTab(tabNum, adapter);
                }
                break;
            case 2:
                FTaskBorrowerInfoFragment fTaskBorrowerInfoFragment = (FTaskBorrowerInfoFragment) getSupportFragmentManager().getFragments().get(currentTabPos);
                if (!fTaskBorrowerInfoFragment.isSaveData()) {
                    DialogHelper.showSaveDialog(this, () -> fTaskBorrowerInfoFragment.saveData(), () -> updateTab(tabNum, adapter));

                } else {
                    updateTab(tabNum, adapter);
                }
                break;
            case 3:
                FTaskCommonOwnerInfoFragment fTaskCommonOwnerInfoFragment = (FTaskCommonOwnerInfoFragment) getSupportFragmentManager().getFragments().get(currentTabPos);
                if (!fTaskCommonOwnerInfoFragment.isSaveData()) {
                    DialogHelper.showSaveDialog(this, () -> fTaskCommonOwnerInfoFragment.saveData(), () -> updateTab(tabNum, adapter));

                } else {
                    updateTab(tabNum, adapter);
                }
                break;
            case 4:
                FTaskPracticalUserInfoFragment fTaskPracticalUserInfoFragment = (FTaskPracticalUserInfoFragment) getSupportFragmentManager().getFragments().get(currentTabPos);
                if (!fTaskPracticalUserInfoFragment.isSaveData()) {
                    DialogHelper.showSaveDialog(this, () -> fTaskPracticalUserInfoFragment.saveData(), () -> updateTab(tabNum, adapter));

                } else {
                    updateTab(tabNum, adapter);
                }
                break;
            case 5:
                FTaskBondsmanInfoFragment fTaskBondsmanInfoFragment = (FTaskBondsmanInfoFragment) getSupportFragmentManager().getFragments().get(currentTabPos);
                if (!fTaskBondsmanInfoFragment.isSaveData()) {
                    DialogHelper.showSaveDialog(this, () -> fTaskBondsmanInfoFragment.saveData(), () -> updateTab(tabNum, adapter));

                } else {
                    updateTab(tabNum, adapter);
                }
                break;
            case 6:
                FTaskCommonBorrowInfoFragment fTaskCommonBorrowInfoFragment = (FTaskCommonBorrowInfoFragment) getSupportFragmentManager().getFragments().get(currentTabPos);
                if (!fTaskCommonBorrowInfoFragment.isSaveData()) {
                    DialogHelper.showSaveDialog(this, () -> fTaskCommonBorrowInfoFragment.saveData(), () -> updateTab(tabNum, adapter));
                } else {
                    updateTab(tabNum, adapter);
                }
                break;
            default:
                updateTab(tabNum, adapter);
                break;
        }
    }

    /**
     * 更新标题
     *
     * @param tabNum
     * @param adapter
     */
    private void updateTab(int tabNum, BaseQuickAdapter adapter) {
        mTaskTabAdapter.getData().get(currentTabPos).setSelect(false);
        mTaskTabAdapter.getData().get(tabNum).setSelect(true);
        adapter.notifyItemChanged(currentTabPos);
        adapter.notifyItemChanged(tabNum);
        showHideFragment(mFragments[tabNum], mFragments[currentTabPos]);
        currentTabPos = tabNum;
    }

    private void startLocation() {
        LocationUtil.getLoader().startLocation();
        AMapLocationClient loader = LocationUtil.getLoader();
        loader.setLocationListener(aMapLocation -> {
            title.append("...");
            title.setLength(0);
            title.append("考察员：" + UserInfoSp.getInstance().getUsername() + "\n")
                    .append("拍照时间：" + TimeUtils.getNowString() + "\n")
                    .append("位置：" + aMapLocation.getProvince() + aMapLocation.getCity() + aMapLocation.getDistrict() + aMapLocation.getStreet() + aMapLocation.getStreetNum() + "\n")
                    .append("经纬度：" + aMapLocation.getLatitude() + "/" + aMapLocation.getLongitude());
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            FTaskFaceOpinionLoanConditionFragment fragment = findFragment(FTaskFaceOpinionLoanConditionFragment.class);
            if (fragment.isSupportVisible()) {

            } else {
                View v = getCurrentFocus();
                if (isShouldHideKeyboard(v, ev)) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onBackPressedSupport() {
        new MaterialDialog.Builder(this)
                .content("退出之后无法继续编辑,确定继续退出吗")
                .positiveText("确定")
                .negativeText("取消")
                .onPositive((dialog, which) -> FTaskDetailActivity.super.onBackPressedSupport())
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REBACK_TASK://退回任务成功
                    setResult(RESULT_OK);
                    finish();
                    break;
                case APPLY_STOP_TASK://终止任务成功
                    setResult(RESULT_OK);
                    finish();
                    break;
            }
        }
    }

    // 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                //使EditText触发一次失去焦点事件
                v.setFocusable(false);
//                v.setFocusable(true); //这里不需要是因为下面一句代码会同时实现这个功能
                v.setFocusableInTouchMode(true);
                return true;
            }
        }
        return false;
    }

    /**
     * 保存
     */
    private void saveInfo() {
        KeyboardUtils.hideSoftInput(this);
        switch (currentTabPos) {
            case 0:

                break;
            case 1:

                break;
            case 2:

                break;
            case 3:

                break;
            case 4:

                break;
            case 5:

                break;
            case 6:

                break;
            case 7:

                break;
            case 8:

                break;
            default:
                break;
        }
    }

    /**
     * 返回工单退回原因
     *
     * @param list
     */
    @Override
    public void returnRebackData(List<ReBackEntity> list) {
        if (type == 3 || type == 4) {
            if (list.size() > 0) {
                mReBackPopup.notifyAdapter(list);
                if (!mReBackPopup.isShowing()) {
                    mViewBinding.titleBar.setTitleDrawable(R.drawable.ic_triangle_black_top);
                }
                mReBackPopup.showPopupWindow(mViewBinding.llyTitleBar);
            } else {
                ToastUtils.showLong("暂时没有退回原因");
            }
        }
    }

    /**
     * 提交成功
     */
    @Override
    public void commitSuccess() {
        setResult(RESULT_OK);
        finish();
    }

    public class ClickHandler {
        public void onDataExamine(View view) {//资料审查
            Bundle bundle = new Bundle();
            bundle.putString("id", id);
            startActivity(FDataExmaineActivity.class, bundle);
        }

        public void onBusinessRemark(View view) {//业务备注
            Bundle bundle = new Bundle();
            bundle.putString("id", id);
            startActivity(BusinessRemarkActivity.class, bundle);
        }

        public void onBackTask(View view) {//退回任务
            Bundle bundle = new Bundle();
            bundle.putString("id", id);
            bundle.putString("reback", reback);
            startActivityForResult(BackTaskActivity.class, bundle, REBACK_TASK);
        }

        public void onApplyStop(View view) {//申请终止
            Bundle bundle = new Bundle();
            bundle.putString("id", id);
            bundle.putString("reback", reback);
            startActivityForResult(ApplyStopActivity.class, bundle, APPLY_STOP_TASK);
        }

        public void onSubmint(View view) {//提交
            mPresenter.commitData(id, reback);
        }
    }
}
